package com.huazi.www.drug.drugz.util;

import java.sql.*;

/**
 * @description：工具类
 * @author：zt
 * @date：2021/5/8 9:20
 * @versions：v1.0
 */
public class BaseDao {

    public static Connection conn;
    public static PreparedStatement ps;
    public static ResultSet rs;

    public Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital?useUnicode=true&characterEncoding=utf8", "root", "123456");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    //关闭的方法
    public void Close(ResultSet rs, PreparedStatement ps, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //增删改通用方法
    public int executeUpdate(String sql, Object... obj) {
        int count = 0;
        conn = getConnection();
        try {
            ps = conn.prepareStatement(sql);
            if (obj.length > 0) {
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject((i + 1), obj[i]);
                }
            }
            count = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            Close(null, ps, conn);
        }
        return count;
    }

    //查询通用方法
    public ResultSet executeQuery(String sql, Object... obj) {
        conn = getConnection();
        try {
            ps = conn.prepareStatement(sql);
            if (obj.length > 0) {
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject((i + 1), obj[i]);
                }
            }
            rs = ps.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return rs;
    }

}

